import random
from dataclasses import dataclass, field

# from PySide6.QtWidgets import QMessageBox

from .equation import Equation
from .add_equation import AddEquation
from .sub_equation import SubEquation


@dataclass
class Exercise:
    equationList: list[Equation] = field(default_factory=list)
    answer: list[int] = field(default_factory=list)
    rightCount: int = 0
    wrongCount: int = 0

    def check(self) -> any:
        # print("exercise-check:", self.answer)
        self.wrongCount = 0     # 重置
        wrongExercise: Exercise = Exercise()
        wrongExercise.equationList.clear()
        for i in range(len(self.equationList)):
            if self.equationList[i].calculate() != self.answer[i]:
                wrongExercise.equationList.append(self.equationList[i])
                wrongExercise.wrongCount += 1
        wrongExercise.rightCount = len(self.equationList) - \
            wrongExercise.wrongCount

        # 重置回答
        self.answer.clear()
        return wrongExercise

    def addAnswer(self, answer: int):
        self.answer.append(answer)

    def getAnswerValue(self, index):
        return self.answer[index]

    def setAnswerValue(self, index: int, answer: int):
        self.answer.insert(index, answer)

    def clearAnswer(self):
        self.answer.clear()

    def generateExercise(self, amountAdd: int, amountSub: int):
        # todo 参数校验
        if Equation.rangeMax - Equation.rangeMin * 2 < 0:
            # reply = QMessageBox.warning(None, "参数错误", "Equation.rangeMax - Equation.rangeMin < 0",
            #                             QMessageBox.Ok | QMessageBox.Cancel, QMessageBox.Cancel)
            raise Exception("参数错误：Equation.rangeMax、Equation.rangeMin 错误")

        # 必须先清空
        self.equationList.clear()

        count: int = 1
        while count <= amountAdd:
            equation = AddEquation()
            # 判断结果区间、查重
            if equation.isBetween() and not self.occursIn(equation):
                count += 1
                self.equationList.append(equation)

        count = 1
        while count <= amountSub:
            equation = SubEquation()
            # 判断结果区间、查重
            if equation.isBetween() and not self.occursIn(equation):
                count += 1
                self.equationList.append(equation)

        random.shuffle(self.equationList)

    def occursIn(self, equation: Equation) -> bool:
        for item in self.equationList:
            if item.isEquals(equation):
                return True
        return False
